package com.kaifamiao.reqeust;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/upload/multiple")
@MultipartConfig(location = "D:/uploads")
public class UploadMultipleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new ServletException( "不支持以GET方式上传文件" );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();

        // 获得用`post`方式提交的`multipart/form-data`表单上所有控件对应的Part对象组成集合
        Collection<Part> parts = request.getParts();
        if( parts == null || parts.isEmpty() ) {
            out.printf( "<p style='color: green'>请选择需要上传的文件后再提交</p>\n" );
            out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
            return;
        }
        for ( Part p : parts ) {
            System.out.println( p );
            // 获得用户上传文件的原始名称
            final String original = p.getSubmittedFileName();
            // 根据原始文件名称是否为空字符串来确定是否有文件待处理
            if( !original.isEmpty() ) {
                try {
                    p.write(original);
                    out.printf( "<p style='color: green'>文件[%s]上传成功</p>", original );
                } catch ( FileAlreadyExistsException e ) {
                    out.printf( "<p style='color: red'>文件[%s]上传失败</p>", original );
                    e.printStackTrace();
                }
            }
        }
        out.println( "<p> <a href='/index.html'>返回首页</a> </p>" );
    }

}
